package cn.edu.pzhu.javaweb.controller;

import java.awt.image.BufferedImage;
import java.io.IOException;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import cn.edu.pzhu.javaweb.util.RandomCharImageGenerator;

/**
 * Servlet implementation class CreateCaptchaServlet
 */
@WebServlet("/captcha")
public class CreateCaptchaServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * 
     * @see HttpServlet#HttpServlet()
     */
    public CreateCaptchaServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		 // 1. 设置响应类型为图像image/jpeg
        response.setContentType("image/jpeg");
        // 禁用缓存，防止浏览器重复使用验证码
        response.setHeader("Pragma", "no-cache");
        response.setHeader("Cache-Control", "no-cache");
        response.setDateHeader("Expires", 0);
        
        // 2. 初始化工具类的实例image
        RandomCharImageGenerator util = new RandomCharImageGenerator();
        util.initialize(80, 30, 4); // 示例：宽80、高30、4个字符
        
        // 3. 获得生成图像的验证码
        String captchaCode = util.getText();
        
        // 4. 将图片输出到前端
        BufferedImage image = util.getImage();
        ImageIO.write(image, "jpeg", response.getOutputStream());
        
        // 5. 将验证码保存到session
        HttpSession session = request.getSession();
        session.setAttribute("SESSION_CAPTCHA", captchaCode);
       }

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}
